using Blog2025.Application.Events;
using Blog2025.Domain.Events;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Blog2025.Application.EventHandlers;

/// <summary>
/// 用户创建事件处理器 - 发送欢迎邮件
/// </summary>
public class UserCreatedWelcomeHandler : INotificationHandler<DomainEventNotification>
{
    private readonly ILogger<UserCreatedWelcomeHandler> _logger;

    public UserCreatedWelcomeHandler(ILogger<UserCreatedWelcomeHandler> logger)
    {
        _logger = logger;
    }

    public async Task Handle(DomainEventNotification notification, CancellationToken cancellationToken)
    {
        // 只处理用户创建事件
        if (notification.DomainEvent is UserCreatedEvent userEvent)
        {
            _logger.LogInformation("开始发送欢迎邮件: 事件ID={EventId}, 用户ID={UserId}, 用户名={Username}", 
                userEvent.EventId, userEvent.UserId, userEvent.Username);

            try
            {
                // 模拟发送欢迎邮件
                await SendWelcomeEmail(userEvent.Username);
                
                _logger.LogInformation("欢迎邮件发送成功: 用户ID={UserId}", userEvent.UserId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "欢迎邮件发送失败: 用户ID={UserId}", userEvent.UserId);
            }
        }
    }

    private async Task SendWelcomeEmail(string username)
    {
        // 模拟发送邮件的异步操作
        await Task.Delay(100);
        _logger.LogInformation("欢迎邮件已发送给用户: {Username}", username);
    }
}
